package com.tjbaobao.videoplayol.listener;

import com.google.gson.Gson;
import com.tjbaobao.framework.utils.Tools;
import com.tjbaobao.videoplayol.message.response.BaseResponse;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 *
 * Created by TJbaobao on 2018/1/12.
 */

public abstract class TJCallback<APIResponse extends BaseResponse> implements Callback {

    @Override
    public void onFailure(Call call, IOException e) {

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if(response!=null&&response.isSuccessful())
        {
            String result = response.body().string();
            APIResponse apiResponse = new Gson().fromJson(result,getEntityClass());
            if(apiResponse!=null)
            {
                if(!apiResponse.getResultCode().equalsIgnoreCase("ok"))
                {
                    if(apiResponse.getMessage()!=null&&apiResponse.getMessage().equals(""))
                    {
                        Tools.showToast(apiResponse.getMessage());
                    }
                    onFailure(call,null);
                }
                else
                {
                    onSuccess(apiResponse);
                }
            }
            else
            {
                onFailure(call,null);
            }

        }
        else
        {
            onFailure(call,null);
        }
    }

    public abstract void onSuccess(APIResponse response);

    private Class<APIResponse> getEntityClass()
    {
        Class <APIResponse> entityClass = (Class <APIResponse>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return entityClass;
    }
}
